<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
  <style>
    header {
      display: flex;
      justify-content: space-between;
      margin: 20px 0;
    }
  </style>
</head>
<body>
  <div class="container">
    <header>
      <div style="display: flex;">
        <input type="text" class="form-control" placeholder="姓名搜索" id="search">
        <button type="button" class="btn btn-primary" style="width: 100px;" onclick="search()">
          搜索
        </button>
        <!-- <button type="button" class="btn btn-primary" style="width: 100px;" onclick="search()">
          重置
        </button> -->
      </div>
      <!-- 新增按钮 -->
      <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" onclick="openModal()">
        新增学生
      </button>
    </header>

    <!-- 新增的弹出框 -->
    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h1 class="modal-title fs-5" id="exampleModalLabel">新增学生</h1>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <!-- 新增的时候的form表单 -->
            <div class="mb-3">
              <label for="exampleFormControlInput1" class="form-label">姓名</label>
              <input type="text" class="form-control" id="exampleFormControlInput1">
            </div>
            <div class="mb-3">
              <label for="exampleFormControlInput2" class="form-label">学号</label>
              <input type="number" min="0" class="form-control" id="exampleFormControlInput2">
            </div>
            <div class="mb-3">
              <label for="exampleFormControlInput3" class="form-label">年龄</label>
              <input type="number" min="0" class="form-control" id="exampleFormControlInput3">
            </div>
            <div class="mb-3">
              <label for="exampleFormControlInput4" class="form-label">性别</label>
              <select class="form-select" aria-label="Default select example" id="exampleFormControlInput4">
                <option selected disabled>--- 请选择 ---</option>
                <option value="1">男</option>
                <option value="2">女</option>
              </select>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" onclick="submit()" data-bs-dismiss="modal">确定</button>
          </div>
        </div>
      </div>
    </div>
    


    <table class="table table-striped">
      <thead>
        <tr>
          <th scope="col">学号</th>
          <th scope="col">姓名</th>
          <th scope="col">年龄</th>
          <th scope="col">性别</th>
          <th scope="col">操作</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>

    <!-- 分页组件 -->
    <nav aria-label="Page navigation example" style="display: flex;justify-content: end;">
      <ul class="pagination">
      </ul>
    </nav>
  </div>


  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>

  <script>
    const token = localStorage.getItem("token");
    if (!token) {
      location.href = "./login.html"
    }


    const pagesize = 3;
    // currentPage表示的是当前的页码
    let currentPage = 1;
    // pages表示的是总页数
    let pages = 0;
    // total表示学生的总数
    let total = 0;
    // 弹出框的标题
    // let modalTitle = "新增学生";
    let status = 1;
    // 表示需要修改的那条数据的id
    let editId = "";


    // 获取表格数据的方法
    const getData = (page = 1, searchValue = "") => {
      // get请求的参数直接拼接在url的后面
      fetch(`http://127.0.0.1:3000/students/list?page=${page}&pagesize=${pagesize}&value=${searchValue}`, {
        method: "GET",
        headers: {
          'Content-Type': 'application/json',
          // 一般情况下token，要放在请求头的里面
          'token': localStorage.getItem("token"),
        },
      })
        .then(response => response.json())
        .then(res => {
          if (res.success) {
            // 拼接了表格的数据
            let str = "";
            res.data.forEach(item => {
              str += `
                <tr>
                  <th scope="row">${item.num}</th>
                  <th scope="row">${item.name}</th>
                  <td>${item.age}</td>
                  <td>${item.sex === 1 ? "男" : "女"}</td>
                  <td style="width:200px">
                    <button type="button" class="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#exampleModal" onclick="editOpen('${item.name}', '${item.num}', '${item.age}', '${item.sex}', '${item._id}')">编辑</button>
                    <button type="button" class="btn btn-danger" onclick="remove('${item._id}')">删除</button>
                  </td>  
                </tr>
              `
            })
            document.querySelector("tbody").innerHTML = str;


            // 拼接分页器
            let str2 = '<li class="page-item" onclick="previous(-1)"><a class="page-link" href="#">Previous</a></li>';
            // 获得总页数
            // res.count是后端返回的数据库的总条数
            total = res.count;
            pages = Math.ceil(total / pagesize);
            for (let i = 1; i <= pages; i++) {
              str2 += `<li class="page-item" onclick="pageclick(${i})"><a class="page-link" href="#">${i}</a></li>`;
            }
            str2 += `<li class="page-item"  onclick="previous(1)"><a class="page-link" href="#">Next</a></li>`;
            document.querySelector(".pagination").innerHTML = str2;
          } else if (res.message === "token无效或者已过期") {
            localStorage.removeItem("token");
            location.href = "./login.html";
          }
        })
    }
    getData(currentPage);
    
  
  
    // 点击页码的事件
    const pageclick = (page) => {
      // console.log("页码被点击了", page);
      currentPage = page;
      // 每次点击页码的时候，都需要重新获取一次数据
      getData(page);
    }

    // 点击上一页
    const previous = (n) => {
      if (n === 1) {
        if (currentPage < pages) {
          // 需要将页码-1
          currentPage += n;
          getData(currentPage);
        }
      } else {
        if (currentPage > 1) {
          // 需要将页码-1
          currentPage += n;
          getData(currentPage);
        }
      }    
    }



    // 删除事件
    const remove = (id) => {
      fetch("http://127.0.0.1:3000/students/del", {
        method: "POST",
        headers: {
          'Content-Type': 'application/json',
          // 一般情况下token，要放在请求头的里面
          'token': localStorage.getItem("token"),
        },
        body: JSON.stringify({id: id})
      })
        .then(response => response.json())
        .then(res => {
          if (res.success) {
            alert(res.message);
            // 为了把最后一页的最后一条数据删除了之后，能跳到前一页
            // 判断当前是否在最后一页，并且判断最后一个是否是由一条数据
            if (currentPage === Math.ceil(total / pagesize) && (total % pagesize === 1)) {
              currentPage = currentPage - 1;
            }
            getData(currentPage);
          } else {
            alert(res.message)
          }
        })
    }
  

    // 打开新增框
    const openModal = () => {
      // 修改弹出框的标题为新增学生
      document.querySelector("#exampleModalLabel").innerHTML = "新增学生";
      status = 1;
      // 清空了表单
      document.querySelector("#exampleFormControlInput1").value = "";
      document.querySelector("#exampleFormControlInput2").value = "";
      document.querySelector("#exampleFormControlInput3").value = "";
      document.querySelector("#exampleFormControlInput4").value = "";
    }

    // 打开编辑框
    const editOpen = (name, num, age, sex, id) => {
      document.querySelector("#exampleModalLabel").innerHTML = "修改学生";
      status = 2;
      // item表示的就是当前这个编辑按钮对应的那一条数据
      // console.log(name, num, age, sex);
      // 打开编辑框的时候，要将对应的这条数据填入表单
      document.querySelector("#exampleFormControlInput1").value = name;
      document.querySelector("#exampleFormControlInput2").value = num;
      document.querySelector("#exampleFormControlInput3").value = age;
      document.querySelector("#exampleFormControlInput4").value = sex;
      editId = id;
    }
  
    // 新增的确认
    const submit = () => {
      // 需要判断当前是新增还是编辑
      // 从而决定要调新增接口还是编辑接口
      if (status === 1) {
        // 应该要优先对表单数据进行正则校验
        fetch("http://127.0.0.1:3000/students/add", {
          method: "POST",
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            name: document.querySelector("#exampleFormControlInput1").value,
            num: document.querySelector("#exampleFormControlInput2").value,
            age: document.querySelector("#exampleFormControlInput3").value,
            sex: document.querySelector("#exampleFormControlInput4").value,
          })
        })
          .then(response => response.json())
          .then(res => {
            if (res.success) {
              // 关闭弹窗
              // 更新数据
              alert(res.message);
              getData(currentPage);
            }
            
          })
      } else {
        fetch("http://127.0.0.1:3000/students/edit", {
          method: "POST",
          headers: {
            'Content-Type': 'application/json'
          },
          // 编辑的时候，除了修改的数据以外，额外多传一个_id（数据库主键）
          // 为了找到我们要修改哪一条数据
          body: JSON.stringify({
            name: document.querySelector("#exampleFormControlInput1").value,
            num: document.querySelector("#exampleFormControlInput2").value,
            age: document.querySelector("#exampleFormControlInput3").value,
            sex: document.querySelector("#exampleFormControlInput4").value,
            id: editId
          })
        })
          .then(response => response.json())
          .then(res => {
            if (res.success) {
              alert(res.message);
              getData(currentPage);
            }
          })
      }
    }


    // 搜索名字功能
    const search = () => {
      // 可以拿到搜索框的值
      // 搜索的时候要回到第一页
      getData(1, document.querySelector("#search").value)
    }
  </script>
</body>
</html>